# -*- coding: utf-8 -*-
# __init__.py create by kumiler on 2025/7/11 10:39
# email:lukunming@jtexpress.com
# desc
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
import sys
import io
from kumiler_platform.ddl_create_script.mysql2hive_v2 import main as process_mysql_to_hive
import json


class MySQLToHiveConverterApp:
    def __init__(self, root):
        """初始化应用程序界面"""
        self.root = root
        self.root.title("MySQL 到 Hive SQL 转换器")  # 设置窗口标题
        self.root.geometry("600x400")  # 设置窗口大小

        # 界面变量
        self.input_file = tk.StringVar()  # 存储输入文件路径
        # 默认输出目录设置为当前工作目录下的hive_output文件夹
        self.output_dir = tk.StringVar(value=os.path.join(os.getcwd(), "hive_output"))
        self.processing = False  # 标记是否正在处理文件

        # 创建界面组件
        self.create_widgets()

    def create_widgets(self):
        """创建所有界面组件"""
        # 主框架
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 标题标签
        ttk.Label(main_frame, text="MySQL 到 Hive SQL 转换器",
                  font=("Microsoft YaHei", 14, "bold")).grid(row=0, column=0, columnspan=3, pady=10)

        # 输入文件选择部分
        ttk.Label(main_frame, text="MySQL SQL 文件:").grid(row=1, column=0, sticky=tk.W, pady=5)
        ttk.Entry(main_frame, textvariable=self.input_file, width=50).grid(row=1, column=1, sticky=tk.W)
        ttk.Button(main_frame, text="浏览...", command=self.browse_input_file).grid(row=1, column=2, padx=5)

        # 输出目录选择部分
        ttk.Label(main_frame, text="输出目录:").grid(row=2, column=0, sticky=tk.W, pady=5)
        ttk.Entry(main_frame, textvariable=self.output_dir, width=50).grid(row=2, column=1, sticky=tk.W)
        ttk.Button(main_frame, text="浏览...", command=self.browse_output_dir).grid(row=2, column=2, padx=5)

        # 进度条
        self.progress = ttk.Progressbar(main_frame, orient=tk.HORIZONTAL, length=400, mode='determinate')
        self.progress.grid(row=3, column=0, columnspan=3, pady=20)

        # 转换按钮
        ttk.Button(main_frame, text="转换为 Hive SQL",
                   command=self.convert_file).grid(row=4, column=0, columnspan=3, pady=10)

        # 状态标签
        self.status_label = ttk.Label(main_frame, text="准备就绪", foreground="green")
        self.status_label.grid(row=5, column=0, columnspan=3, pady=10)

        # 下载按钮(初始状态为禁用)
        self.download_btn = ttk.Button(main_frame, text="下载结果文件",
                                       state=tk.DISABLED, command=self.download_result)
        self.download_btn.grid(row=6, column=0, columnspan=3, pady=10)

    def browse_input_file(self):
        """打开文件选择对话框选择MySQL SQL文件"""
        file_path = filedialog.askopenfilename(
            title="选择MySQL SQL文件",
            filetypes=[("SQL文件", "*.sql"), ("所有文件", "*.*")]
        )
        if file_path:
            self.input_file.set(file_path)
            self.status_label.config(text="已选择输入文件", foreground="green")

    def browse_output_dir(self):
        """打开目录选择对话框选择输出目录"""
        dir_path = filedialog.askdirectory(title="选择输出目录")
        if dir_path:
            self.output_dir.set(dir_path)
            self.status_label.config(text="已设置输出目录", foreground="green")

    def convert_file(self):
        """执行文件转换操作"""
        if self.processing:  # 防止重复处理
            return

        input_path = self.input_file.get()
        output_path = self.output_dir.get()

        # 验证输入
        if not input_path:
            messagebox.showerror("错误", "请先选择MySQL SQL文件")
            return

        if not os.path.isfile(input_path):
            messagebox.showerror("错误", "输入的MySQL文件不存在")
            return

        # 准备配置JSON
        config = {
            "MYSQL_SQL_DIR": input_path,
            "HIVE_SQL_DIR": output_path,
            "TBLPROPERTIES": {
                "CREATOR": "GUI用户",
                "SOURCE_SYSTEM": "mysql",
                "TRANSLATED_FROM": "mysql",
                "SYNCH_RULE": "full"
            }
        }

        try:
            self.processing = True
            self.status_label.config(text="正在转换...", foreground="blue")
            self.progress.start(10)  # 启动进度条动画

            # 调用转换函数
            process_mysql_to_hive(json.dumps(config))

            # 获取生成的Hive SQL文件
            table_name = os.path.splitext(os.path.basename(input_path))[0]
            self.result_file = os.path.join(output_path, f"mysql_{table_name}.hql")

            # 更新UI状态
            self.progress.stop()
            self.status_label.config(text="转换完成!", foreground="green")
            self.download_btn.config(state=tk.NORMAL)  # 启用下载按钮
            messagebox.showinfo("成功", "文件转换完成!")

        except Exception as e:
            self.progress.stop()
            self.status_label.config(text=f"转换失败: {str(e)}", foreground="red")
            messagebox.showerror("错误", f"转换过程中出错:\n{str(e)}")
        finally:
            self.processing = False

    def download_result(self):
        """处理下载结果文件操作"""
        if hasattr(self, 'result_file') and os.path.isfile(self.result_file):
            # 在实际应用中，这里可以添加文件下载逻辑
            # 例如通过电子邮件发送或提供直接下载链接
            messagebox.showinfo("下载", f"结果文件已保存到:\n{self.result_file}")
        else:
            messagebox.showerror("错误", "找不到结果文件")


def main():
    """主函数，启动GUI应用"""
    root = tk.Tk()
    try:
        # 设置Windows风格界面
        root.style = ttk.Style()
        root.style.theme_use('winnative')
    except:
        pass

    app = MySQLToHiveConverterApp(root)
    root.mainloop()


if __name__ == '__main__':
    main()